package com.adgox.tiantianbiting.listen.history;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.adapter.CollectAdapter;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ShareUrlBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.listen.find_like.FindLikeActivity;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.adgox.tiantianbiting.utils.WebviewActivity;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HistoryActivity extends AppCompatActivity implements CollectAdapter.onItemClickListener, View.OnClickListener {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.ll_empty)
    LinearLayout llEmpty;
    private int userId;
    private int currentPage = 1;
    private int maxPage = 10;
    private int totalPage;
    private CollectAdapter adapter;
    private int clickPosition;
    private List<SubProgramBean> datas = new ArrayList<>();
    private Dialog findLikeDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        ButterKnife.bind(this);
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        userId = ((UserInfo) SessionManager.getDefault().getUser()).getId();
        init();
    }

    private void init() {
        if (adapter != null) adapter.clear();
        if (datas != null) datas.clear();
        currentPage = 1;
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!rv.canScrollVertically(1)) {
                    if (currentPage < totalPage) {
                        currentPage++;
                        getData(currentPage);
                    } else {
                        Toast.makeText(HistoryActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
        getData(1);
    }

    private void getData(int startPoint) {
        showLoading();
        OkGo.<BaseResponseBean<PageBean<SubProgramBean>>>get(ApiConstant.BASE_URL + ApiConstant.GET_HISTORY_AND_COLLECT + userId + "/0")
                .params("startPoint", startPoint)
                .params("maxPage", maxPage)
                .execute(new JsonCallback<BaseResponseBean<PageBean<SubProgramBean>>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<PageBean<SubProgramBean>>> response) {
                        DialogUtils.dismiss();
                        if (!"0".equals(response.body().getCode()) || response.body().getData() == null || response.body().getData().getData() == null ||
                                response.body().getData().getData().size() == 0) {
                            Toast.makeText(HistoryActivity.this, response.body().getMessage() == null ? "获取数据失败" : response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            llEmpty.setVisibility(View.VISIBLE);
                            rv.setVisibility(View.GONE);
                            return;
                        }
                        setDatas(response.body().getData());
                    }
                });
    }

    private void showLoading() {
        DialogUtils.showLoadingDialog(this);
    }

    private void setDatas(PageBean<SubProgramBean> data) {
        llEmpty.setVisibility(View.GONE);
        rv.setVisibility(View.VISIBLE);
        totalPage = data.getTotalPages();
        datas.addAll(data.getData());
        if (adapter == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            rv.setLayoutManager(layoutManager);
            adapter = new CollectAdapter(data.getData());
            adapter.setOnItemClickListener(this);
            rv.setAdapter(adapter);
        } else {
            adapter.addDatas(data.getData());
            adapter.notifyDataSetChanged();
        }
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @Override
    public void onItemClick(View view, CollectAdapter.ViewName viewName, int position) {
        if (viewName == CollectAdapter.ViewName.FINDLIKE) {
            clickPosition = position;
            popFindLikeDialog(view);
        } else if (viewName == CollectAdapter.ViewName.ITEM) {
            Intent intent = new Intent(this, ProgramDetailActivity.class);
            intent.putExtra("programId", datas.get(position).getId());
            intent.putExtra("programName", datas.get(position).getTitle());
            startActivity(intent);
        }
    }

    private void popFindLikeDialog(View view) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_find_like, null);
        findLikeDialog = new Dialog(this, R.style.TransparentDialog);
        findLikeDialog.setContentView(inflate);

        FrameLayout flFind = findLikeDialog.findViewById(R.id.fl_find);
        FrameLayout flTop = findLikeDialog.findViewById(R.id.fl_top);
        FrameLayout flCollect = findLikeDialog.findViewById(R.id.fl_collect);
        TextView tvCollect = findLikeDialog.findViewById(R.id.tv_collect);
        FrameLayout flShare = findLikeDialog.findViewById(R.id.fl_share);

        tvCollect.setText(datas.get(clickPosition).getMarkStatus() == 0 ? "取消收藏" : "收藏");

        flFind.setOnClickListener(this);
        flTop.setOnClickListener(this);
        flCollect.setOnClickListener(this);
        flShare.setOnClickListener(this);

        Window window = findLikeDialog.getWindow();
        window.setGravity(Gravity.RIGHT | Gravity.TOP);
        WindowManager.LayoutParams attributes = window.getAttributes();
        int[] positions = new int[2];
        view.getLocationOnScreen(positions);
        attributes.y = positions[1];
        attributes.x = 100;
        window.setAttributes(attributes);
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        findLikeDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_find:
                Intent intent = new Intent(this, FindLikeActivity.class);
                intent.putExtra("categoryId", datas.get(clickPosition).getCategoryId());
                startActivity(intent);
                if (findLikeDialog != null) findLikeDialog.dismiss();
                break;
            case R.id.fl_top:
                //收藏置顶
                setTop();
                if (findLikeDialog != null) findLikeDialog.dismiss();
                break;
            case R.id.fl_collect:
                HashMap<String, Object> map = new HashMap<>();
                map.put("programId", datas.get(clickPosition).getId());
                map.put("status", 2);
                map.put("seasonId", 1);
                map.put("userId", userId);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                if (datas.get(clickPosition).getMarkStatus() == 0) {
                    cancelCollect(s);
                } else {
                    addCollect(s);
                }
                findLikeDialog.dismiss();
                break;
            case R.id.fl_share:
                share();
                findLikeDialog.dismiss();
                break;
        }
    }

    private void share() {
        OkGo.<BaseResponseBean<ShareUrlBean>>get(ApiConstant.BASE_URL+ApiConstant.GET_SHARE_URL)
                .params("flg","go_download")
                .execute(new JsonCallback<BaseResponseBean<ShareUrlBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<ShareUrlBean>> response) {
                        if ("0".equals(response.body().getCode())&&response.body().getData()!=null){
                            DialogUtils.showShareDialog(HistoryActivity.this,response.body().getData().getLocation());
                        } else {
                            Toast.makeText(HistoryActivity.this, "获取分享信息失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void addCollect(String s) {
        DialogUtils.showLoadingDialog(this);
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.ADD_COLLECT_AND_HISTORY)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        DialogUtils.dismiss();
                        if ("0".equals(response.body().getCode())) {
                            datas.clear();
                            if (adapter != null) adapter.clear();
                            init();
                        } else {
                            Toast.makeText(HistoryActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void cancelCollect(String s) {
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.CANCEL_COLLECT)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        DialogUtils.dismiss();
                        if ("0".equals(response.body().getCode())) {
                            init();
                        } else {
                            Toast.makeText(HistoryActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void setTop() {
        OkGo.<BaseResponseBean<String>>get(ApiConstant.BASE_URL + ApiConstant.SET_TOP)
                .params("userId", userId)
                .params("programId", datas.get(clickPosition).getId())
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        if ("0".equals(response.body().getCode())) {
                            init();
                        } else {
                            Toast.makeText(HistoryActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}
